#!/usr/bin/env jq
# compile-code-Makefile -- Generates a GNU Makefile with recipes for the compiled processes considering their dependencies
##

def mktarget(suffix): "\(.).\(suffix)";
def mktargets(suffix): map(mktarget(suffix)) | join(" ");
def mktarget: mktarget("done");
def mktargets: mktargets("done");

.deepdive_.execution.dependencies |
{ path: "Makefile", content: [

# make variables
"
# default commands
define CMD_data
endef
define CMD_process
endef
define CMD_factor
endef
define TOUCH
endef
define RESET
rm -f
endef

.DEFAULT: help
help:
	@echo make list
	@echo make list-targets
	@echo make all
	@echo make reset
list:
	@printf \"%s\\n\" \(keys | map(@sh) | join(" "))
list-targets:
	@printf \"make %s\\n\" \(keys | map(mktarget | @sh) | join(" "))
	@echo \"make     FOO.reset       # resets  FOO.done\"
	@echo \"make -tB FOO.done        # assumes FOO.done\"
	@echo \"make TOUCH=    FOO.done  # shows what still needs to run to get FOO.done\"
	@echo \"make TOUCH= -B FOO.done  # shows everything that needs to run to get FOO.done\"
all: \(keys | mktargets)
reset: \(keys | mktargets("reset"))
.PHONY: help list list-targets all reset %.reset

", ( to_entries[]

# make target and recipe for every node in the dependency graph
| "
\(.key | mktarget): \(.value | mktargets)
	$(CMD_\(.key | sub("/.*"; "")))
	$(TOUCH)

\(.key | mktarget("reset")):
	$(RESET) \(.key | mktarget("done"))
"

)

] | join("") }
